import type { ComponentStyleIdType } from '../../../types/interfaces'
import { BaseModule } from '../../../lib/abstract'
import { removeStandardStyleTag } from '../../../lib/style_injector'
import { ToolKit } from '../../../lib/utils/toolkit'
import {
  ComponentStyleId,
  CustomElementStyleId,
  getPlatformValue,
  HOSTNAME,
  logger,
} from '../../../types/constants'
import { ThemeSourceMode } from '../../../types/interfaces'
import { createThemeService } from '../../../user_center/tab/personalization/custom_css/theme'
import { ConfigManager } from '../../config_manager'

interface Config {
  enabled?: boolean
}

export class ThemeStyle extends BaseModule {
  readonly id: string = 'theme_style'
  readonly styleId: string = ComponentStyleId[this.name]
  isInitialized: boolean = false
  readonly supportedPlatforms: string[] = ConfigManager.getInstance().moduleSupportedPlatforms(this.name)
  private static instance: ThemeStyle
  private readonly themeService = createThemeService(getPlatformValue(HOSTNAME))

  config: Config = {
    enabled: true,
  }

  get name(): ComponentStyleIdType {
    return 'ThemeStyle'
  }

  /**
   * 获取单例实例
   */
  public static getInstance(): ThemeStyle {
    if (!ThemeStyle.instance) {
      ThemeStyle.instance = new ThemeStyle()
    }
    return ThemeStyle.instance
  }

  destroy(): void {
    removeStandardStyleTag(CustomElementStyleId.ThemeCss)
    this.setRangeDisabledStatus(true)
  }

  core(): void {
    this.loadConfig()

    if (!this.config.enabled)
      return

    this.applyThemeStyle()
  }

  onToggleCallback(_id: string, checked: boolean): void {
    super.onToggleCallback(_id, checked)
  }

  applyThemeStyle(): void {
    this.themeService?.registerThemeStyles(ToolKit.browser.theme.getCurrentTheme(ThemeSourceMode.LOCAL_STORAGE), CustomElementStyleId.ThemeCss)
    this.setRangeDisabledStatus(false)
  }

  applyConfig(config: Partial<Config>): void {
    super.updateConfig(config)

    this.applyThemeStyle()

    logger.info(`[${this.name}] Config updated and apply`, this.config)
  }

  /**
   * 设置用户中心-个性化-搜索设置-展示列数的禁用状态
   */
  setRangeDisabledStatus(disabled: boolean): void {
    $('.user-center-modal input[type="range"]#search_result_columns').prop('disabled', disabled)
  }

  getStyles(): string {
    return `
`
  }
}
